﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using Daycare.Models;
using Daycare.Services;

namespace Daycare
{
    public partial class InfoManagement : System.Web.UI.Page
    {
        /* Variables */
        ConfigurationSettingsService configSettingsService;
        DocumentService documentService;
        UserService userService;

        /* Evant Handling */
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
              

                PopulateConfigurationSettingsDropDownList();

                ConfigurationSetting queriedConfig;
                if (Request.QueryString.HasKeys())
                {
                    int configurationSettingsId = 0;
                    Int32.TryParse(Request.QueryString["ConfigurationSettingsId"], out configurationSettingsId);

                    if (configurationSettingsId > 0)
                    {
                        queriedConfig = configSettingsService.GetConfigurationSetting(configurationSettingsId);

                        if (queriedConfig != null)
                        {
                            ddlConfigurations.SelectedValue = queriedConfig.configurationSettingsId.ToString();
                            ddlConfigurations_SelectedIndexChanged(ddlConfigurations, new EventArgs());
                        }

                    }
                }

                LockDownUnauthorizedUsers();
            }
        }

        protected void HeaderTab_Click(object sender, EventArgs e)
        {
            LinkButton clickedTab = (LinkButton)sender;

            switch (clickedTab.ID)
            {
                case "lbDocumentsTab":
                    if(lbDocumentsTab.CssClass == "tab selected")
                    {
                        lbDocumentsTab.CssClass = "tab";
                        accDocuments.SelectedIndex = -1;
                    }
                    else
                    {
                        lbDocumentsTab.CssClass = "tab selected";
                        PopulateDocumentTabConfigurationSettings();
                    }
                    
                    break;
                case "lbSchedulingTab":
                    if (lbSchedulingTab.CssClass == "tab selected")
                    {
                        lbSchedulingTab.CssClass = "tab";
                        accScheduling.SelectedIndex = -1;
                    }
                    else
                    {
                        lbSchedulingTab.CssClass = "tab selected";
                    }
                    
                    break;
            }
        }

        protected void ddlDocumentTypes_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlDocumentTypes.SelectedIndex > 0)
            {
                tbDocumentTypeName.Text = ddlDocumentTypes.SelectedItem.Text;

                bAddUpdateDocumentTypeName.CommandName = "Update";
                bAddUpdateDocumentTypeName.Text = "Update Document Type";

                bDeleteDocumentType.Enabled = true;
            }
            else
            {
                tbDocumentTypeName.Text = String.Empty;

                bAddUpdateDocumentTypeName.CommandName = "Add";
                bAddUpdateDocumentTypeName.Text = "Add Document Type";

                bDeleteDocumentType.Enabled = false;
            }
        }

        protected void bDeleteDocumentType_Click(object sender, EventArgs e)
        {
            documentService = new DocumentService();
            DocumentType dType = new DocumentType(Int32.Parse(ddlDocumentTypes.SelectedValue), ddlDocumentTypes.SelectedItem.Text);

            bool isDeleted = documentService.DeleteDocumentType(dType);
            String statusMessage = String.Empty;

            if (isDeleted)
            {
                PopulateDocumentTabConfigurationSettings();

                tbDocumentTypeName.Text = String.Empty;

                bAddUpdateDocumentTypeName.CommandName = "Add";
                bAddUpdateDocumentTypeName.Text = "Add Document Type";

                bDeleteDocumentType.Enabled = false;

                statusMessage = "<h3>Success!</h3>Document type deleted successfully.<br />";
            }
            else
            {
                statusMessage = "<h3>Deletion Incomplete</h3>Document type could not be deleted. If the document type is associated <br />to any documents it cannot be deleted without first deleting those associated documents.";
            }

            PopupService.ShowPopup((AjaxControlToolkit.ModalPopupExtender)Page.Master.FindControl("mpeStatus"), statusMessage);
        }

        protected void bAddUpdateDocumentTypeName_Click(object sender, EventArgs e)
        {
            Button button = (Button)sender;
            documentService = new DocumentService();
            String statusMessage = String.Empty;

            switch (button.CommandName)
            {
                case "Add":
                    if (tbDocumentTypeName.Text.Length > 0)
                    {
                        bool uniqueName = true;

                        foreach (ListItem documentType in ddlDocumentTypes.Items)
                        {
                            if (documentType.Text == tbDocumentTypeName.Text)
                            {
                                uniqueName = false;

                                tbDocumentTypeName.BackColor = ColorTranslator.FromHtml("#3D3D3D");
                                tbDocumentTypeName.ForeColor = Color.White;

                                statusMessage = "<h3>Error</h3><ul><li>Document name must be unique.</li></ul>";
                                break;
                            }
                        }

                        if (uniqueName)
                        {
                            bool successfulAddition = documentService.AddDocumentType(tbDocumentTypeName.Text);

                            if (successfulAddition)
                            {
                                tbDocumentTypeName.BackColor = Color.White;
                                tbDocumentTypeName.ForeColor = Color.Black;

                                statusMessage = "<h3>Success!</h3>Document type added successfully.<br />";

                                PopulateDocumentTabConfigurationSettings();
                            }
                            else
                            {
                                tbDocumentTypeName.BackColor = ColorTranslator.FromHtml("#3D3D3D");
                                tbDocumentTypeName.ForeColor = Color.White;

                                statusMessage = "<h3>Error</h3>An error occurred during document type creation.<br />";
                            }
                        }
                    }
                    else
                    {
                        tbDocumentTypeName.BackColor = ColorTranslator.FromHtml("#3D3D3D");
                        tbDocumentTypeName.ForeColor = Color.White;

                        statusMessage = "<h3>Error</h3><ul><li>Document name is required.</li></ul>";
                    }

                    break;
                case "Update":
                    if (tbDocumentTypeName.Text.Length > 0)
                    {
                        int nameCount = 0;

                        foreach (ListItem documentType in ddlDocumentTypes.Items)
                        {
                            if (documentType.Text == tbDocumentTypeName.Text)
                            {
                                nameCount++;
                            }
                        }

                        if (nameCount > 0)
                        {
                            tbDocumentTypeName.BackColor = ColorTranslator.FromHtml("#3D3D3D");
                            tbDocumentTypeName.ForeColor = Color.White;

                            statusMessage = "<h3>Error</h3><ul><li>Document name must be unique.</li></ul>";
                        }
                        else
                        {
                            DocumentType dType = new DocumentType(Int32.Parse(ddlDocumentTypes.SelectedValue), tbDocumentTypeName.Text);
                            bool successfulUpdate = documentService.UpdateDocumentType(dType);

                            if (successfulUpdate)
                            {
                                tbDocumentTypeName.BackColor = Color.White;
                                tbDocumentTypeName.ForeColor = Color.Black;

                                statusMessage = "<h3>Success!</h3>Document type updated successfully.<br />";

                                PopulateDocumentTabConfigurationSettings();

                                tbDocumentTypeName.Text = String.Empty;

                                bAddUpdateDocumentTypeName.CommandName = "Add";
                                bAddUpdateDocumentTypeName.Text = "Add Document Type";

                                bDeleteDocumentType.Enabled = false;
                            }
                            else
                            {
                                tbDocumentTypeName.BackColor = ColorTranslator.FromHtml("#3D3D3D");
                                tbDocumentTypeName.ForeColor = Color.White;

                                statusMessage = "<h3>Error</h3>An error occurred during document type update.<br />";
                            }
                        }
                    }
                    else
                    {
                        tbDocumentTypeName.BackColor = ColorTranslator.FromHtml("#3D3D3D");
                        tbDocumentTypeName.ForeColor = Color.White;

                        statusMessage = "<h3>Error</h3><ul><li>Document name is required.</li></ul>";
                    }

                    break;
            }

            PopupService.ShowPopup((AjaxControlToolkit.ModalPopupExtender)Page.Master.FindControl("mpeStatus"), statusMessage);
        }

        protected void ddlConfigurations_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(ddlConfigurations.SelectedIndex > 0)
            {
                configSettingsService = new ConfigurationSettingsService();
                ConfigurationSetting config = configSettingsService.GetConfigurationSetting(Int32.Parse(ddlConfigurations.SelectedValue));

                switch (config.configurationSettingsGroupName)
                {
                    case "Documents":
                        if (accDocuments.SelectedIndex != 0)
                        {
                            HeaderTab_Click(lbDocumentsTab, new EventArgs());
                            accDocuments.SelectedIndex = 0;
                        }
                        break;
                }
            }
        }

        /* Helper Functions */
        protected void PopulateConfigurationSettingsDropDownList()
        {
            configSettingsService = new ConfigurationSettingsService();

            ddlConfigurations.AppendDataBoundItems = true;
            ddlConfigurations.Items.Clear();
            ddlConfigurations.Items.Add(new ListItem("Select One", "0"));
            ddlConfigurations.DataTextField = "configurationSettingsName";
            ddlConfigurations.DataValueField = "configurationSettingsId";
            ddlConfigurations.DataSource = configSettingsService.GetConfigurationSettings();
            ddlConfigurations.DataBind();
        }

        protected void PopulateDocumentTabConfigurationSettings()
        {
            documentService = new DocumentService();

            ddlDocumentTypes.AppendDataBoundItems = true;
            ddlDocumentTypes.Items.Clear();
            ddlDocumentTypes.Items.Add(new ListItem("Add One", "0"));
            ddlDocumentTypes.DataTextField = "DocumentTypeName";
            ddlDocumentTypes.DataValueField = "DocumentTypeId";
            ddlDocumentTypes.DataSource = documentService.GetDocumentTypes();
            ddlDocumentTypes.DataBind();
        }

        protected void LockDownUnauthorizedUsers()
        {
            userService = new UserService();
            int employeeId = Int32.Parse(HttpContext.Current.Profile.GetPropertyValue("EmployeeId").ToString());
            Employee emp = userService.GetEmployee(employeeId);

            if (!Roles.IsUserInRole("Administration"))
            {
                bAddUpdateDocumentTypeName.Enabled = false;
                bDeleteDocumentType.Enabled = false;
                ddlConfigurations.Enabled = false;
                ddlDocumentTypes.Enabled = false;
                tbDocumentTypeName.Enabled = false;
                accDocuments.Enabled = false;
                accScheduling.Enabled = false;
            }
        }
    }
}